#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org
# Copyright (C) 2019 X-WRT <dev@x-wrt.com>

START=11

x_wrt_install_vps() {
	local DEVS=$(fdisk -l | grep -o "^/dev.*" | head -n1 | awk '{print $1}')
	DEVS="$DEVS /dev/sda1 /dev/vda1 /dev/xvda1"
	DEVS=$(for dev in $DEVS; do echo $dev; done | sort | uniq)
	for dev in $DEVS; do
		test -b $dev && {
			mkdir -p /tmp/block
			mount $dev /tmp/block && {
				test -e /tmp/block/x-wrt-install-vps.sh && {
					sleep 60
					cp /tmp/block/x-wrt-install-vps.sh /tmp/
					umount /tmp/block
					rmdir /tmp/block
					sh /tmp/x-wrt-install-vps.sh
					return 0
				}
				umount /tmp/block
			}
			rmdir /tmp/block
		}
	done
}

x_wrt_base_setup() {
	uname -m | grep -q x86 || return 0

	#allow all input
	local idx=0
	while uci get firewall.@zone[$idx] >/dev/null 2>&1; do
		uci set firewall.@zone[$idx].input='ACCEPT'
		idx=$((idx+1))
	done
	uci commit firewall

	#enable dropbear ssh
	uci set dropbear.@dropbear[0].PasswordAuth='on'
	uci set dropbear.@dropbear[0].RootPasswordAuth='on'
	uci commit dropbear
}

x_wrt_flash() {
	sleep 90
	test -f /tmp/usb_reset/x-wrt-sysupgrade-force* && \
	cp /tmp/usb_reset/x-wrt-sysupgrade-force* /tmp/ && \
	sysupgrade -n -F /tmp/x-wrt-sysupgrade-force*

	rm -f /tmp/x-wrt-sysupgrade-force*

	test -f /tmp/usb_reset/x-wrt-sysupgrade* && \
	cp /tmp/usb_reset/x-wrt-sysupgrade* /tmp/ && \
	sysupgrade -n /tmp/x-wrt-sysupgrade*

	rm -f /tmp/x-wrt-sysupgrade*
}

boot() {
	mount | grep -q "^/dev" || {
		x_wrt_base_setup
		x_wrt_install_vps &
	}

	local DEV=`test -f /rom/etc/sda.ready && echo /dev/sdb1 || echo /dev/sda1`
	mkdir /tmp/usb_reset || return 0
	mount $DEV /tmp/usb_reset || {
		rmdir /tmp/usb_reset
		return 0
	}

	#check and enable ssh
	if test -f /tmp/usb_reset/x-wrt-ssh || test -f /tmp/usb_reset/x-wrt-ssh.txt; then
		uci set dropbear.@dropbear[0].PasswordAuth='on'
		uci set dropbear.@dropbear[0].RootPasswordAuth='on'
		uci commit dropbear
	fi

	#check and do sysupgrade
	if test -f /tmp/usb_reset/x-wrt-sysupgrade*; then
		x_wrt_flash &
		return 0
	fi

	#check and do facotry reset
	if test -f /tmp/usb_reset/x-wrt-reset || test -f /tmp/usb_reset/x-wrt-reset.txt; then
		rm -f /tmp/usb_reset/x-wrt-reset*
		/usr/sbin/system_reset -y -r
		return 0
	fi

	umount /tmp/usb_reset
	rmdir /tmp/usb_reset
	return 0
}
